package di.scanner.io;

import di.scanner.exception.XMLNotFoundException;
import di.scanner.helper.XMLHelper;
import di.scanner.producer.FileProducer;
import di.scanner.producer.Producer;
import di.scanner.store.XMLStore;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

public class FileScanner {

    private Producer producer;

    public FileScanner() {
        producer = new FileProducer();
    }

    public void produce(String srcPath) {
        File dir = new File(srcPath);
        File[] files = dir.listFiles();
        if (files == null) {
            return;
        }
        for (File file : files) {
            if (file.isDirectory()) {
                produce(file.getAbsolutePath());
            } else {
                producer.produce(file);
            }
        }
    }

    public void scan(String path){
        File  rootFile = new File(path);
        if (!rootFile.exists()){
            System.out.println("not a path");
            return;
        }
        LinkedList<File> fileLinkedList = new LinkedList<File>();
        File[] files = rootFile.listFiles();
        scan(fileLinkedList, files);
        File tempFile ;
        while (!fileLinkedList.isEmpty()){
            tempFile = fileLinkedList.removeFirst();
            files = tempFile.listFiles();
             scan(fileLinkedList, files);
        }
        producer.produce(null);//终结标志

        scanXML();

    }

    private void scanXML() {
        try {
            List<String> targetNames=XMLHelper.getTargetClassNameFromDocuments(XMLHelper.parseXmlToDocuments(XMLStore.getInstance().getXmlFilePaths()),false);
            for(String name:targetNames){
                System.out.println(name);
            }
            List<String> restful = XMLHelper.getRestDtoClassNameList();
            for (String str:restful) {
                System.out.println(str);
            }
        } catch (XMLNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void scan(LinkedList<File> fileLinkedList, File[] files) {
        for (File file:files){
            if (file.isDirectory()){
                fileLinkedList.add(file);
            } else {
                producer.produce(file);
            }
        }

    }


}
